package com.shjn.squirrel.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.AccountLoginReq;
import com.shjn.squirrel.bean.httpBean.RespCommonResult;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.customView.RecyclerDigitalKeyboard;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.RecyclerInfoCache;
import com.shjn.squirrel.utils.ForbiddenSysKeyBoardUtils;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.shjn.squirrel.utils.PhoneCheckUtils;
import com.shjn.squirrel.utils.SoundPlayUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 回收员账号密码登录（手机号）
 */
public class RecyclerTeleFragment extends BaseFragment {

    private static RecyclerTeleFragment instance;
    private EditText mEditAccount;
    private EditText mEditPassword;
    private RecyclerDigitalKeyboard mDigitalKeyboard;

    public RecyclerTeleFragment() {
    }

    public synchronized static RecyclerTeleFragment getInstance() {
        if (instance == null) {
            instance = new RecyclerTeleFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.recycler_tele_login, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initKeyboard();

    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        mActivity.mBackAndTimer.setOnBackListener(new BackAndTimerView.OnBackListener() {
            @Override
            public void onBack() {
                //返回回收员扫码登录页
                if (!RecyclerScanFragment.getInstance().isAdded()) {
                    SoundPlayUtils.enablePlay = true;
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, RecyclerScanFragment.getInstance())
                            .commit();
                }
            }
        }).setBackVisibleState(true).setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
            @Override
            public void onTimerFinish() {
                //返回回收员扫码登录页
                if (!RecyclerScanFragment.getInstance().isAdded()) {
                    SoundPlayUtils.enablePlay = true;
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, RecyclerScanFragment.getInstance())
                            .commit();
                }
            }
        }).setTime(60).setVisibleState(true).start();
    }

    /**
     * editview与键盘初始化
     */
    private void initKeyboard() {
        mDigitalKeyboard = (RecyclerDigitalKeyboard) mView.findViewById(R.id.recycler_digital_keyboard);
        mEditAccount = (EditText) mView.findViewById(R.id.ed_account);
        mEditPassword = (EditText) mView.findViewById(R.id.ed_password);
        //清空editview,设置默认焦点
        mEditAccount.post(new Runnable() {
            @Override
            public void run() {
                mEditAccount.getText().clear();
            }
        });
        mEditAccount.post(new Runnable() {
            @Override
            public void run() {
                mEditAccount.requestFocus();
            }
        });
        mEditPassword.post(new Runnable() {
            @Override
            public void run() {
                mEditPassword.getText().clear();
            }
        });
        //禁止弹出系统键盘，屏蔽长按事件
        ForbiddenSysKeyBoardUtils.bannedSysKeyBoard(mActivity, mEditAccount);
        ForbiddenSysKeyBoardUtils.bannedSysKeyBoard(mActivity, mEditPassword);
        //监听账号文本框数字变化
        mEditAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

            }

            //手机号344显示
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence == null || charSequence.length() == 0) return;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < charSequence.length(); i++) {
                    if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(charSequence.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(charSequence.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    mEditAccount.setText(sb.toString());
                    mEditAccount.setSelection(index);
                }
            }

            @Override
            public void afterTextChanged(Editable charSequence) {
                if (charSequence.length() < 13) {
                    SoundPlayUtils.enablePlay = true;
                } else {
                    SoundPlayUtils.enablePlay = false;
                }
            }
        });

        //设置键盘切换事件
        mEditAccount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isfocused) {
                if (isfocused) {
                    mDigitalKeyboard.setEditText(mEditAccount);
                    if (mEditAccount.getText().length() < 13) {
                        SoundPlayUtils.enablePlay = true;
                    } else {
                        SoundPlayUtils.enablePlay = false;
                    }
                }
            }
        });
        mEditPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isfocused) {
                if (isfocused) {
                    mDigitalKeyboard.setEditText(mEditPassword);
                    SoundPlayUtils.enablePlay = false;
                }
            }
        });
        //登录
        mDigitalKeyboard.setOnConfirmListener(new RecyclerDigitalKeyboard.OnConfirmListener() {
            @Override
            public void onConfirm() {
                //执行登录操作
                if (!RecyclerSelectFragment.getInstance().isAdded() && !WarningDialog.getInstance().isAdded()) {
                    //禁用返回键，暂停倒计时器（登录操作可能有延时）
                    mActivity.mBackAndTimer.setBackEnable(false).stop();
                    if (mEditAccount.getText().length() == 13 && mEditPassword.getText().length() >= 6) {
                        if (PhoneCheckUtils.isPhoneLegal(mEditAccount.getText().toString())) {
                            SoundPlayUtils.enablePlay = true;
                            RecyclerInfoCache.telNum = PhoneCheckUtils.getRealTel(mEditAccount.getText().toString());
                            //----------测试用-------------//
                            RecyclerInfoCache.loginState = true;
                            //跳转到垃圾选择页面
                            if (!RecyclerSelectFragment.getInstance().isAdded()) {
                                mActivity.getFragmentManager().beginTransaction()
                                        .replace(R.id.mid, RecyclerSelectFragment.getInstance())
                                        .commit();
    }
                            //启用返回键
                            mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mActivity.mBackAndTimer.setBackEnable(true);
                                }
                            });
                            //----------测试用-------------//
                            //上传到服务器上验证
//                            OkhttpHelper.postRequest(Constant.baseUrl + "machine/verification/recyclerLoginByAccount",
//                                    new Gson().toJson(new AccountLoginReq(LocalStorage.getDeviceID(MyApplication.getInstance()), RecyclerInfoCache.telNum, mEditPassword.getText().toString())),
//                                    new Callback() {
//                                        @Override
//                                        public void onFailure(Call call, IOException e) {
//                                            Log.i("info", "recyclerLoginByAccount_onFailure: " + e.getMessage());
//                                            //启用返回键，继续倒计时
//                                            mActivity.runOnUiThread(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
//                                                }
//                                            });
//                                        }
//
//                                        @Override
//                                        public void onResponse(Call call, Response response) {
//                                            try {
//                                                RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
//                                                if (result.getStateCode() == 1) {
//                                                    RecyclerInfoCache.loginState = true;
//                                                    //跳转到垃圾选择页面
//                                                    if (!RecyclerSelectFragment.getInstance().isAdded()) {
//                                                        mActivity.getFragmentManager().beginTransaction()
//                                                                .replace(R.id.mid, RecyclerSelectFragment.getInstance())
//                                                                .commit();
//                                                    }
//                                                    //启用返回键
//                                                    mActivity.runOnUiThread(new Runnable() {
//                                                        @Override
//                                                        public void run() {
//                                                            mActivity.mBackAndTimer.setBackEnable(true);
//                                                        }
//                                                    });
//                                                } else {
//                                                    WarningDialog.getInstance()
//                                                            .setMessage("您输入的账号和密码有误请重新输入")
//                                                            .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
//                                                                @Override
//                                                                public void onCloseDialog() {
//                                                                    //启用返回键，继续倒计时
//                                                                    mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
//                                                                    mEditAccount.getText().clear();
//                                                                    mEditPassword.getText().clear();
//                                                                }
//                                                            })
//                                                            .show(mActivity.getFragmentManager(), "recycler_login_error");
//
//                                                }
//                                            } catch (IOException e) {
//                                                //启用返回键，继续倒计时
//                                                mActivity.runOnUiThread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
//                                                    }
//                                                });
//                                            }
//                                        }
//                                    });


                        } else {
                            WarningDialog.getInstance()
                                    .setMessage("您输入的账号格式有误请重新输入")
                                    .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                        @Override
                                        public void onCloseDialog() {
                                            //启用返回键，继续倒计时
                                            mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                            mEditAccount.getText().clear();
                                        }
                                    })
                                    .show(mActivity.getFragmentManager(), "recycler_login_error");
                        }

                    } else if (mEditAccount.getText().length() < 13 && mEditPassword.getText().length() >= 6) {
                        WarningDialog.getInstance()
                                .setMessage("您输入的账号格式有误请重新输入")
                                .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                    @Override
                                    public void onCloseDialog() {
                                        //启用返回键，继续倒计时
                                        mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                        mEditAccount.getText().clear();
                                    }
                                })
                                .show(mActivity.getFragmentManager(), "recycler_login_error");

                    } else if (mEditAccount.getText().length() == 13 && mEditPassword.getText().length() < 6) {
                        if (PhoneCheckUtils.isPhoneLegal(mEditAccount.getText().toString())) {
                            WarningDialog.getInstance()
                                    .setMessage("您输入的密码格式有误请重新输入")
                                    .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                        @Override
                                        public void onCloseDialog() {
                                            //启用返回键，继续倒计时
                                            mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                            mEditPassword.getText().clear();
                                        }
                                    })
                                    .show(mActivity.getFragmentManager(), "recycler_login_error");

                        } else {
                            WarningDialog.getInstance()
                                    .setMessage("您输入的账号和密码格式有误请重新输入")
                                    .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                        @Override
                                        public void onCloseDialog() {
                                            //启用返回键，继续倒计时
                                            mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                            mEditAccount.getText().clear();
                                            mEditPassword.getText().clear();
                                        }
                                    })
                                    .show(mActivity.getFragmentManager(), "recycler_login_error");
                        }

                    } else {
                        WarningDialog.getInstance()
                                .setMessage("您输入的账号和密码格式有误请重新输入")
                                .setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                                    @Override
                                    public void onCloseDialog() {
                                        //启用返回键，继续倒计时
                                        mActivity.mBackAndTimer.setBackEnable(true).setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                                        mEditAccount.getText().clear();
                                        mEditPassword.getText().clear();
                                    }
                                })
                                .show(mActivity.getFragmentManager(), "recycler_login_error");
                    }
                }
            }
        });

    }
}
